<!-- 添加或修改参数配置对话框 -->
<template>
  <div>
    <px-form ref="formRef" :rules="rules" class="equip-form" :model="formValue" label-width="120px">
      <EditDropDown dropdownTitle="设备信息">
        <template v-slot:content>
          <px-row>
            <px-col :span="8">
              <px-form-item label="设备ID" prop="eqpId">
                <px-input v-model="formValue.eqpId" maxlength="50" disabled placeholder="请输入设备ID" clearable />
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-form-item label="设备名称" prop="eqpName">
                <px-input v-model="formValue.eqpName" maxlength="50" placeholder="请输入设备名称" clearable />
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-form-item label="设备编号" prop="showName">
                <px-input v-model="formValue.showName" maxlength="50" placeholder="请输入设备编号" clearable />
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
            </px-col>
            <px-col :span="8">
              <EquipSystemTree
                :isRequired="true"
                :className="formValue.className"
                :systemCode="formValue.systemCode"
                currentType="edit"
                @changeAllSystemCodes="changeAllSystemCodes"
                @changeSystemCodes="changeSystemCodes"
                @clearSystem="clearSystem"
                @getEditSystemCodes="getEditSystemCodes"
              />
            </px-col>
            <px-col :span="8">
              <EquipCategorySelect
                :isRequired="true"
                :className="formValue.className"
                :systemCodes="systemCodes"
                :categoryId="formValue.categoryId"
                @changeCategory="changeCategory"
              />
            </px-col>
            <px-col :span="8">
              <EquipTypeSelect
                :isRequired="true"
                :className="formValue.className"
                :systemCodes="systemCodes"
                :categoryId="formValue.categoryId"
                :typeId="formValue.typeId"
                @changeType="changeType"
              />
            </px-col>
            <px-col :span="8">
              <EquipModelSelect
                :isRequired="true"
                :className="formValue.className"
                :systemCodes="systemCodes"
                :categoryId="formValue.categoryId"
                :typeId="formValue.typeId"
                :modelId="formValue.modelId"
                @changeModel="changeModel"
              />
            </px-col>
            <px-col :span="8">
              <px-form-item label="设备位置" prop="positionCode">
                <px-cascader
                  ref="cascaderRef"
                  v-model="formValue.positionCode"
                  style="width: 100%"
                  :props="{ children: 'children', label: 'name', value: 'code', checkStrictly: true }"
                  :options="positionList"
                  placeholder="请先选择厂区"
                  clearable
                  filterable
                  @change="cascaderRef.togglePopperVisible()"
                />
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-form-item label="资产编码" prop="poCode">
                <px-input v-model="formValue.poCode" maxlength="50" placeholder="请输入资产编码" clearable />
              </px-form-item>
            </px-col>
            <px-col :span="16">
              <px-form-item label="管理属性" prop="manageAttr">
                <px-checkbox-group v-model="formValue.manageAttr">
                  <px-checkbox label="1">计量器具</px-checkbox>
                  <px-checkbox label="2">特种设备</px-checkbox>
                  <px-checkbox label="3">定期校验仪器仪表</px-checkbox>
                </px-checkbox-group>
              </px-form-item>
            </px-col>
          </px-row>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="其他信息">
        <template v-slot:content>
          <px-row>
            <px-col :span="8">
              <px-form-item label="合同名称" prop="htName">
                <px-input v-model="formValue.htName" maxlength="50" placeholder="请输入合同名称" clearable />
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-form-item label="合同编号" prop="htCode">
                <px-input v-model="formValue.htCode" maxlength="50" placeholder="请输入合同编号" clearable />
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-form-item label="设备厂家" prop="manufacturer">
                <px-input v-model="formValue.manufacturer" maxlength="50" placeholder="请输入设备厂家" clearable />
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-form-item label="厂家联系人" prop="manufacturerContact">
                <px-input v-model="formValue.manufacturerContact" maxlength="50" placeholder="请输入厂家联系人" clearable />
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-form-item label="厂家联系电话" prop="manufacturerPhone">
                <px-input v-model="formValue.manufacturerPhone" maxlength="50" placeholder="请输入厂家联系电话" clearable />
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-form-item label="设备负责人" prop="principalId">
                <px-select-v2
                  v-model="formValue.principalId"
                  style="width: 100%"
                  filterable
                  clearable
                  :options="principalList"
                  placeholder="请选择设备负责人"
                  @change="principalChange"
                  @focus="focusPrincipalId"
                />
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-form-item label="出厂日期" prop="manufactureDate">
                <px-date-picker
                  v-model="formValue.manufactureDate"
                  style="width: 100%"
                  placeholder="请选择出厂日期"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  @change="changeStartTime"
                />
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-form-item label="质保结束日期" prop="warrantyEndDate">
                <px-date-picker
                  v-model="formValue.warrantyEndDate"
                  style="width: 100%"
                  placeholder="请选择质保结束日期"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  @change="changeEndTime"
                />
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-form-item label="设备定值" prop="constantVal">
                <px-input v-model="formValue.constantVal" maxlength="50" placeholder="请输入设备定值" clearable />
              </px-form-item>
            </px-col>
            <px-col :span="24">
              <px-form-item label="设备描述" prop="description">
                <px-input
                  v-model="formValue.description"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  maxlength="1000"
                  placeholder="请输入设备描述"
                />
              </px-form-item>
            </px-col>
            <px-col :span="24">
              <px-form-item label="设备图片" prop="pictureList">
                <PhotoUpload
                  photoType="add"
                  :photoData="{ moduleName: 'eqp' }"
                  :photoList="formValue.pictureList"
                  @changePhotoList="changePhotoList"
                  @savePhotoStatus="savePhotoStatus"
                />
              </px-form-item>
            </px-col>
          </px-row>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="自定义扩展信息">
        <template v-slot:content>
          <div style="width: 100%">
            <px-button type="primary" style="margin-bottom: 20px" plain icon="Plus" @click="handleAdd">新增扩展信息</px-button>
            <px-form ref="extRecordRef" :model="extForm">
              <px-table v-if="extForm.extInfoMap && extForm.extInfoMap.length !== 0" :data="extForm.extInfoMap" border>
                <px-table-column fixed="left" type="index" width="60" label="序号" />
                <px-table-column fixed="left" prop="key" label="扩展信息名称" min-width="160" show-overflow-tooltip>
                  <template #default="scope">
                    <template v-if="isEdit(scope.$index)">
                      <px-form-item
                        label-width="0px"
                        label=""
                        style="margin-top: 16px"
                        :prop="'extInfoMap.' + scope.$index + '.key'"
                        :rules="[{ required: true, message: '请输入扩展信息名称', trigger: 'blur' }]"
                      >
                        <px-input v-model="scope.row.key" placeholder="请输入扩展信息名称" maxlength="50" clearable />
                      </px-form-item>
                    </template>
                    <template v-else>{{ scope.row.key }}</template>
                  </template>
                </px-table-column>
                <px-table-column fixed="left" prop="value" label="扩展内容" min-width="160" show-overflow-tooltip>
                  <template #default="scope">
                    <template v-if="isEdit(scope.$index)">
                      <px-form-item
                        label-width="0px"
                        label=""
                        style="margin-top: 16px"
                        :prop="'extInfoMap.' + scope.$index + '.value'"
                        :rules="[{ required: true, message: '扩展内容不能为空', trigger: ['blur', 'change'] }]"
                      >
                        <px-input v-model="scope.row.value" placeholder="请输入扩展内容" maxlength="50" clearable />
                      </px-form-item>
                    </template>
                    <template v-else>{{ scope.row.value }}</template>
                  </template>
                </px-table-column>
                <px-table-column label="操作">
                  <template #default="scope">
                    <px-tooltip v-if="isEdit(scope.$index)" content="添加" placement="top">
                      <px-button link icon="Check" type="primary" @click="handleCheck(extRecordRef, scope.$index, scope.row)" />
                    </px-tooltip>
                    <px-tooltip v-else content="编辑" placement="top">
                      <px-button link icon="EditPen" type="primary" @click="handleEdit(scope.row, scope.$index)" />
                    </px-tooltip>
                    <px-tooltip v-if="isEdit(scope.$index)" content="取消" placement="top">
                      <px-button link icon="Close" type="primary" @click="handleCancel(scope.row)" />
                    </px-tooltip>
                    <px-tooltip v-else content="删除" placement="top">
                      <px-button link icon="Delete" type="danger" @click="handleDelete(scope.$index)" />
                    </px-tooltip>
                  </template>
                </px-table-column>
              </px-table>
            </px-form>
          </div>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="相关资料">
        <template v-slot:content>
          <!-- <FileUpload
              fileType="edit"
              :actionUrl="'/ifp/dms/api/v1/doc/upload'"
              :downloadUrl="'/ifp/dms/api/v1/doc/download'"
              :fileData="{ parentId }"
              :fileList="formValue.extFileList"
              style="margin-bottom: 18px"
              :isCustomUpload="true"
              @changeFileList="changeFileList"
              @saveFileStatus="saveFileStatus"
            /> -->
          <FileUpload
            fileType="edit"
            :fileData="{ moduleName: 'eqp' }"
            :fileList="formValue.extFileList"
            style="margin-bottom: 18px"
            @changeFileList="changeFileList"
            @saveFileStatus="saveFileStatus"
          />
        </template>
      </EditDropDown>
      <div class="edit-equip-empty-dev" />
    </px-form>
    <!--空白dev用来占位，撑起底部内容-->
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" :disabled="photoStatusFlag || fileStatusFlag" @click="handleSubmit(formRef)">确认</px-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { updateEquipment } from "@/api/equip/archive";
import { getTableData } from "@/api/system/positionManage";
import FileUpload from "@/components/Upload/FileUpload.vue";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import { throttleDelay as delay } from "@/utils/constant";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipCategorySelect from "@/views/all/equip/components/EquipCategorySelect.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipModelSelect from "@/views/all/equip/components/EquipModelSelect.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import EquipTypeSelect from "@/views/all/equip/components/EquipTypeSelect.vue";
import { useThrottleFn } from "@vueuse/core";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watchEffect } from "vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);

// 父级传过来的值
const props = defineProps(["activeName", "eqpDetailData"]);

// 页面本身的值
const formRef = ref();
const cascaderRef = ref();
const extRecordRef = ref();
const state = reactive<any>({
  formValue: {
    className: "",
    systemCode: "",
    categoryId: null,
    typeId: null,
    modelId: null
  },
  principalList: [], // 责任人下拉框
  positionList: [],
  photoStatusFlag: false,
  fileStatusFlag: false,
  editIndex: -1,
  extForm: {
    extInfoMap: []
  },
  parentId: "", // 上传文件的文件夹id
  fileIdList: [], // 已经上传的文件的id
  systemCodes: []
});
const { formValue, principalList, photoStatusFlag, fileStatusFlag, positionList, editIndex, extForm, parentId, fileIdList, systemCodes } =
  toRefs(state);

// 表单校验规则
const rules = computed(() => ({
  eqpId: [{ required: true, message: "设备ID不能为空", trigger: "blur" }],
  eqpName: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
  positionCode: [{ required: true, message: "设备位置不能为空", trigger: "blur" }]
}));

// 新的文件列表
const changeFileList = async val => {
  formValue.value.extFileList = val;
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};

watchEffect(async () => {
  if (props.activeName === "eqp") {
    const { pictureList, className, categoryId, typeId, extInfoMap, manageAttr } = props.eqpDetailData;
    extForm.value.extInfoMap = extInfoMap || [];
    formValue.value = { ...props.eqpDetailData, pictureList: pictureList || [], manageAttr: manageAttr ? manageAttr.split(",") : [] };
    systemCodes.value = [];
    principalList.value = await getEmployeeIdAndName();
    positionList.value = await getTableData({});
  }
});

// 返回主页面
const backMainPage = () => {
  formValue.value = {
    className: "",
    systemCode: "",
    categoryId: null,
    typeId: null,
    modelId: null
  };
  formRef.value?.resetFields();
  extForm.value.extInfoMap = [];
  emits("backMainPage");
};

// 获取借用人的名字
const principalChange = val => {
  formValue.value.principalName = principalList.value.find(item => item.value === val).label;
};

// 开始时间
const changeStartTime = () => {
  if (formValue.value.manufactureDate && formValue.value.warrantyEndDate) {
    if (formValue.value.manufactureDate > formValue.value.warrantyEndDate) {
      formValue.value.warrantyEndDate = formValue.value.manufactureDate;
    }
  }
};
// 结束时间
const changeEndTime = () => {
  if (formValue.value.manufactureDate && formValue.value.warrantyEndDate) {
    if (formValue.value.manufactureDate > formValue.value.warrantyEndDate) {
      formValue.value.manufactureDate = formValue.value.warrantyEndDate;
    }
  }
};

const isEdit = index => index === editIndex.value;

const handleAdd = () => {
  extForm.value.extInfoMap?.push({});
  editIndex.value = extForm.value.extInfoMap.length - 1;
};

const handleCheck = async (formEl, index, row) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      extForm.value.extInfoMap.splice(index, 1, row);
      editIndex.value = -1;
      PxMessage.success("保存成功");
    }
  });
};
const handleEdit = (row, index) => {
  editIndex.value = index;
};

const handleDelete = async index => {
  extForm.value.extInfoMap.splice(index, 1);
  editIndex.value = -1;
  PxMessage.success("删除成功");
};

const handleCancel = row => {
  editIndex.value = -1;
  if (!row.key) {
    extForm.value.extInfoMap.pop();
  }
};

const handleSubmit = useThrottleFn(async (formEl: any) => {
  if (!formEl) return;

  await formEl.validate(async valid => {
    if (valid) {
      extRecordRef.value.validate(async valid => {
        if (valid) {
          const pictureList = [];
          if (formValue.value.pictureList && formValue.value.pictureList.length > 0) {
            formValue.value.pictureList.forEach(item => {
              if (item?.id) {
                pictureList.push(item.id);
              } else if (item?.response.data.id) {
                pictureList.push(item.response.data.id);
              }
            });
          }

          const fileList = [];
          if (formValue.value.extFileList && formValue.value.extFileList.length > 0) {
            formValue.value.extFileList.forEach(item => {
              if (item?.id) {
                fileList.push(item.id);
              } else if (item?.response.data.id) {
                fileList.push(item.response.data.id);
              }
            });
          }

          const { positionCode, manageAttr } = formValue.value;

          await updateEquipment({
            ...formValue.value,
            pictureList,
            extFileList: fileList,
            ...extForm.value,
            positionCode: Array.isArray(positionCode) ? positionCode[positionCode?.length - 1] : positionCode,
            manageAttr: manageAttr ? manageAttr.join(",") : ""
          });
          PxMessage.success("编辑成功");
          backMainPage();
          emits("queryTable");
        }
      });
    }
  });
}, delay);
// 新的图片列表
const changePhotoList = val => {
  formValue.value.pictureList = val;
};
// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  systemCodes.value = [];
  if (!isOnlyClass) {
    formRef.value?.resetFields(["systemCode", "categoryId", "typeId", "modelId", "principalId"]);
  }
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  formValue.value.className = val2;
  formValue.value.systemCode = val3;
  systemCodes.value = val4;
  formRef.value?.resetFields(["categoryId", "typeId", "modelId"]);
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  formValue.value.systemCode = val;
  systemCodes.value = val2;
  formRef.value?.resetFields(["categoryId", "typeId", "modelId"]);
};
// 系统组件值改变触发
const clearSystem = val => {
  systemCodes.value = [];
  formRef.value?.resetFields(["systemCode", "categoryId", "typeId", "modelId"]);
};
// 用于编辑时的页面回显，保证类型型号过滤是正确的
const getEditSystemCodes = (val, val2) => {
  formValue.value.systemCode = val;
  systemCodes.value = val2;
};
// 改变设备总称，清空设备类型和设备型号
const changeCategory = val => {
  formValue.value.categoryId = val;
  formRef.value?.resetFields(["typeId", "modelId"]);
};
// 改变设备类型，清空设备型号
const changeType = (val, val2) => {
  formValue.value.categoryId = val2;
  formValue.value.typeId = val;
  formRef.value?.resetFields(["modelId"]);
};
// 改变设备型号
const changeModel = (val, val2, val3) => {
  formValue.value.categoryId = val2;
  formValue.value.typeId = val3;
  formValue.value.modelId = val;
};
// 获取当前科室人接口
const focusPrincipalId = async () => {
  const param = formValue.value.className ? [formValue.value.className] : [];
  const data = await getEmployeeIdAndName(param);
  principalList.value = JSON.parse(JSON.stringify(data));
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
.info-form-btns {
  position: fixed;
}

.edit-equip-empty-dev {
  height: 50px;
}
</style>
